package com.hmkj.core.api.juhe.bean.epay.endpoints;
import com.hmkj.core.api.juhe.bean.epay.base.DcEndPoint;
import com.hmkj.core.api.juhe.bean.epay.base.MD5;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Description: 双乾扫码支付接口
 * Created by shiyaxiang on 2017/1/3 17:36.
 */
public class ScanPayEndPoint extends DcEndPoint {

    private final String scanCodePayment = "https://scan.95epay.cn/ScanCodePayment.action";


    public ScanPayEndPoint(String md5key, String merNo, String payType) {
        super(md5key, merNo, payType);
    }


    /**
     * 双乾扫码支付
     * @param billNo 商户订单号
     * @param amount 订单总金额,接口中涉及的金额默认以元为单位，精确到分，默认币种为人民币
     * @param paymentType 支付渠道
     * @param merRemark 商户备注
     * @param notifyUrl 异步通知订单结果到商户服务器
     * @param subject 显示在用户app上的订单信息
     * @param desc 对订单的描述
     * @param tranCode 交易服务码 固定：SMZF010
     * @param userId 用户ID 支付宝支付时，要求上送用户在支付宝的唯一用户号
                    获取流程请参考文档说明：
                    https://doc.open.alipay.com/docs/doc.htm?treeId=220&articleId=105337&docType=1#s5,获取buyer_user_id
                    微信支付时，要求上送用户在子商户subAppid下唯一标识
                    获取流程请参考文档说明：
                    http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html------获取openid
                    注：建议使用静默授权

     * @param operatorId 商户操作员编号
     * @param storeId 商户门店编号
     * @param subAppid 子商户微信公众账号ID 微信支付必须上送，并且人工报备到我公司公众号下。
     * @param extend1 备用
     * @param extend2 备用
     */
    public void scanCodePayment(String billNo, String amount,String paymentType, String merRemark, String notifyUrl, String subject
            ,String desc,String tranCode,String userId,String operatorId,String storeId,String subAppid,String extend1,
                                String extend2) {

        String MD5info = "";   	    // 加密字符串

        MD5 md5 = new MD5();
        Map<String, String> map = new TreeMap<>();

        String[] md5Map = new String[]{ merNo, billNo, amount, payType };
        String[] md5ReqMap = new String[]{ "MerNo", "BillNo", "Amount", "PayType"};
        for (int i = 0; i < md5ReqMap.length; i++) {
            map.put(md5ReqMap[i], md5Map[i]);
        }
        StringBuilder b = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()){
            b.append(entry.getKey());
            b.append('=');
            if (entry.getValue() != null){
                b.append(entry.getValue());
            }
            b.append("&");
        }
        String strBeforeMd5 = b.toString() + md5.getMD5ofStr(md5key);
        MD5info = md5.getMD5ofStr(strBeforeMd5);

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(scanCodePayment);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        formparams.add(new BasicNameValuePair("MerNo", merNo));
        formparams.add(new BasicNameValuePair("BillNo", billNo));
        formparams.add(new BasicNameValuePair("Amount", amount));
        formparams.add(new BasicNameValuePair("PayType", payType));
        formparams.add(new BasicNameValuePair("MD5info", MD5info));
        formparams.add(new BasicNameValuePair("TranCode", tranCode));
        formparams.add(new BasicNameValuePair("PaymentType", paymentType));
        formparams.add(new BasicNameValuePair("MerRemark", merRemark));
        formparams.add(new BasicNameValuePair("NotifyURL", notifyUrl));
        formparams.add(new BasicNameValuePair("subject", subject));
        formparams.add(new BasicNameValuePair("desc", desc));
        formparams.add(new BasicNameValuePair("userId", userId));
        formparams.add(new BasicNameValuePair("operatorId", operatorId));
        formparams.add(new BasicNameValuePair("storeId", storeId));
        formparams.add(new BasicNameValuePair("subAppid", subAppid));
        formparams.add(new BasicNameValuePair("extend1", extend1));
        formparams.add(new BasicNameValuePair("extend2", extend2));

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String args[]) {
        ScanPayEndPoint endPoint = new ScanPayEndPoint("12345678","168885",PayType.SMZF.name());
        String MerNo = "168885";   // 商户号
        String BillNo = String.valueOf(System.currentTimeMillis()); // 商户订单号
        String Amount = "0.01"; 	// 订单金额(元)
        String PayType = "SMZF";    // 支付方式
        String MD5info = "";   	    // 加密字符串

        String PaymentType = "WXZF";   // 支付渠道
        String MerRemark = "测试支付";    // 备注
        String NotifyURL = "http://218.4.23.150:8081/95epayDemo/NotifyInfo";   // 异步通知地址

        String subject = "商户测试交易";   // 显示在用户app上的订单信息
        String desc = "info";          // 对订单的描述
        String TranCode = "SMZF010";   // 交易服务码

        String userId = "";     // 用户ID
        String operatorId = ""; // 如员工编号
        String storeId = "";   	// 商户的门店编号
        String subAppid = ""; 	// 子商户微信公众账号ID
        String extend1 = "";   // 备用域1
        String extend2 = "";   // 备用域2

        if(PaymentType.equals("ZFBZF")) {
            userId = "2088022747929295";
        }else if(PaymentType.equals("WXZF")) {
            userId = "oP7_Zs7cAcHNu6zBG172bEJm9TGk";
        }

        endPoint.scanCodePayment(BillNo,Amount,PaymentType,MerRemark,NotifyURL,subject,desc,TranCode,userId,operatorId,storeId,subAppid,extend1,extend2);
    }

}
